package org.sky.lintCode.start;

import java.util.*;

/**
 * 请给一个无序的 HashMap 排序（按 key 的字典序），并返回排序后 Map
 * 样例
 * 输入：
 * [Sunmo:40, Jane:46, Tony:30, Beggar:26]
 * 输出：
 * {Beggar=26, Jane=46, Sunmo=40, Tony=30}
 * 输入：
 * [LingHu:36, Sunmo:20, Emperor:40, Jane:27, Haly:21, Orgen:32]
 * 输出：
 * {Emperor=40, Haly=21, Jane=27, LingHu=36, Orgen=32, Sunmo=20}
 *
 * @author fog
 * @date 2021/11/16
 */

public class HashMapSort {

    public static void main(String[] args) {

        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("Sunmo", 40);
        hashMap.put("Jane", 46);
        hashMap.put("Tony", 30);
        hashMap.put("Beggar", 26);
        hashMap.put("Beggar", 24);
        hashMap.put("Baggar", 24);

        Object[] key = hashMap.keySet().toArray();
        Arrays.sort(key);

        // 渐变方法
        LinkedHashMap<String,Integer> resultMap=new LinkedHashMap<>();

        for (int i = 0; i < key.length; i++) {
            resultMap.put(String.valueOf(key[i]),hashMap.get(key[i]));
        }

        for (String name : resultMap.keySet()) {
            System.out.println(name);
        }

        // hashMapSort(hashMap);

    }

    /**
     *  todo 原理。还未搞懂
     */
    private static void hashMapSort(HashMap<String, Integer> map) {

        StringBuffer nameBuffer = new StringBuffer();

        // 调换 key - value
        HashMap<Integer, String> nameMap = new HashMap<>();

        for (String name : map.keySet()) {

            char[] chars = name.toCharArray();

            nameBuffer.append(chars[0]);

            // nameMap.put(name, String.valueOf(chars[0]));

        }

        String[] split = String.valueOf(nameBuffer).split("");
        Arrays.sort(split, String.CASE_INSENSITIVE_ORDER);

        LinkedHashMap<String, Integer> resultMap = new LinkedHashMap<>();

        for (int i = 0; i < split.length; i++) {
            System.out.println(nameMap.get(split[i]));
            resultMap.put(nameMap.get(split[i]), map.get(nameMap.get(split[i])));
        }

        System.out.println("======================");

        for (String name : resultMap.keySet()) {
            System.out.println(name);
        }

    }

}
